package com.sskj.mine.ui.activity;


import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.base.App;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.bean.CoinFeeBean;
import com.sskj.mine.bean.rxbus.AddressBean;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.WithdrawActivityPresenter;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

@Route(path = RConfig.MIME_WITHDRAW)//提现
public class WithdrawActivity extends BaseActivity<WithdrawActivityPresenter> {

    @BindView(R2.id.tvMoney)
    TextView tvMoney;
    @BindView(R2.id.etAddress)
    EditText etAddress;
    @BindView(R2.id.ivAddress)
    ImageView ivAddress;
    @BindView(R2.id.etNum)
    EditText etNum;
    @BindView(R2.id.tvAll)
    TextView tvAll;
    @BindView(R2.id.view_line)
    View viewLine;
    @BindView(R2.id.tvUnit)
    TextView tvUnit;
    @BindView(R2.id.tvMaxNum)
    TextView tvMaxNum;
    @BindView(R2.id.etPayPwd)
    EditText etPayPwd;
    @BindView(R2.id.tvGetCode)
    TextView tvGetCode;
    @BindView(R2.id.etCode)
    EditText etCode;
    @BindView(R2.id.btWithdraw)
    Button btWithdraw;
    @BindView(R2.id.tvFee)
    TextView tvFee;
    @Autowired
    String code;
    @Autowired
    String id;
    @Autowired
    String usableFund;
    String minCoin;
    String maxCoin;
    private DisposableSubscriber<Long> disposableSubscriber;
    private String mTb_fee;
    private Double wallone;
    private Double walloneMoset;
    @Inject
    UserViewModel userViewModel;
    private String tel;
    private UserData userData;

    @Override
    protected int getLayoutResId() {
        return R.layout.mine_activity_withdraw;
    }

    @Override
    public WithdrawActivityPresenter getPresenter() {
        return new WithdrawActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        setTitle(App.INSTANCE.getString(R.string.mineWithdrawActivity0));
        etNum.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});
        mPresenter.getWithdrawFee(id);
        setRightImg(R.mipmap.mine_icon_recharge_record, v -> {
            ARouter.getInstance().build(RConfig.MINE_ASSERT_RECORD)
                    .withString(Constans.ID, id)
                    .withString(Constans.CODE, code)
                    .navigation();
        });
        //获取验证码
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                ClickUtil.click(tvGetCode, () -> {
                    if (TextUtils.isEmpty(userData.getWay())) {
                        ToastUtil.showShort(App.INSTANCE.getString(R.string.mineRechargeActivity6));
                        return;
                    }
                    if (userData.getWay().equals("mobile")) {
                        mPresenter.sendCode(userData.getMobile());
                    }
                    if (userData.getWay().equals("email")) {
                        mPresenter.sendEmailCode(userData.getMail());
                    }
                });
            }
        });

        //获取提币地址
        ClickUtil.click(ivAddress, () -> {
            ARouter.getInstance().build(RConfig.MINE_WALLET_ADDRESS_MANAGER).withBoolean(Constans.IS_WITHDRAW, true).navigation();
        });

        tvUnit.setText(code);
        tvMoney.setText(usableFund + " " + code);
        //提币
        ClickUtil.click(btWithdraw, () -> {
            if (TextUtils.isEmpty(etAddress.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineWithdrawActivity1));
                return;
            }
            if (TextUtils.isEmpty(etNum.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineWithdrawActivity2));
                return;
            }
            Double aDouble = Double.valueOf(etNum.getText().toString());
            if (aDouble < Double.valueOf(minCoin)) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.mineWithdrawActivity3), minCoin));
                return;
            }
            if (aDouble > Double.valueOf(maxCoin)) {
                ToastUtil.showShort(String.format(App.INSTANCE.getString(R.string.mineWithdrawActivity4), maxCoin));
                return;
            }
            if (aDouble > new BigDecimal(wallone).add(new BigDecimal("-" + mTb_fee).divide(new BigDecimal("100"))).doubleValue()) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineWithdrawActivity7));
                return;
            }
            if (TextUtils.isEmpty(etPayPwd.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineWithdrawActivity8));
                return;
            }
            if (TextUtils.isEmpty(etCode.getText())) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineWithdrawActivity9));
                return;
            }
            mPresenter.withdraw(etCode.getText().toString().trim(),
                    etPayPwd.getText().toString().trim(),
                    etNum.getText().toString().trim(),
                    etAddress.getText().toString().trim(),
                    id,
                    userData.getWay().equals("mobile") ? userData.getMobile() : userData.getMail());
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAddress(AddressBean addressBean) {
        etAddress.setText(addressBean.getAddress());
    }

    public void startCount() {
        tvGetCode.setEnabled(false);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                tvGetCode.setText(time + "s 后重新获取");
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                tvGetCode.setText(App.INSTANCE.getString(R.string.mineWithdrawActivity11));
                tvGetCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    public void updateCoin(CoinFeeBean data) {
        wallone = Double.valueOf(usableFund);
        walloneMoset = Double.valueOf(TextUtils.isEmpty(data.getTb_max()) ? "0" : data.getTb_max());
        mTb_fee = TextUtils.isEmpty(data.getTb_fee()) ? "0" : data.getTb_fee();
        tvMaxNum.setText(App.INSTANCE.getString(R.string.mineWithdrawActivity12) + usableFund);
        ClickUtil.click(tvAll, () -> {
            BigDecimal allBig = new BigDecimal(usableFund).add(new BigDecimal("-" + mTb_fee));
            if (allBig.doubleValue() <= 0) {
                etNum.setText(NumberUtil.keep4("0"));
            } else {
                etNum.setText(NumberUtil.keep4(allBig.toPlainString()));
            }
        });
        tvFee.setText(App.INSTANCE.getString(R.string.mineWithdrawActivity14) + mTb_fee + "个");
        minCoin = TextUtils.isEmpty(data.getTb_min()) ? "0" : data.getTb_min();
        maxCoin = TextUtils.isEmpty(data.getTb_max()) ? "0" : data.getTb_max();
        etNum.setHint(String.format(App.INSTANCE.getString(R.string.mineWithdrawActivity15),
                TextUtils.isEmpty(data.getTb_min()) ? "null" : data.getTb_min(),
                TextUtils.isEmpty(data.getTb_max()) ? "null" : data.getTb_max()));
    }

    @Override
    protected void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void withDrawSuccess() {
        userViewModel.update();
        finish();
    }
}
